<!-- V-webapp/src/views/MyOrdersView.vue -->
<template>
  <div class="orders-container">
    <div class="page-header">
      <el-button @click="$router.back()" class="back-btn" type="primary" link>
        <el-icon><ArrowLeft /></el-icon>
      </el-button>
      <h2>我的订单</h2>
    </div>

    <!-- 订单状态筛选 -->
    <div class="order-filter">
      <el-radio-group v-model="filterStatus" @change="fetchMyOrders">
        <el-radio-button label="all">全部</el-radio-button>
        <el-radio-button label="pending">待支付</el-radio-button>
        <el-radio-button label="paid">已支付</el-radio-button>
        <el-radio-button label="completed">已完成</el-radio-button>
        <el-radio-button label="cancelled">已取消</el-radio-button>
      </el-radio-group>
    </div>

    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>

    <div v-else-if="orders.length === 0" class="empty-container">
      <el-empty description="暂无订单记录">
        <el-button type="primary" @click="$router.push('/products')">
          去购物
        </el-button>
      </el-empty>
    </div>

    <div v-else class="orders-list">
      <div 
        v-for="order in orders" 
        :key="order.order_id"
        class="order-card"
      >
        <div class="order-header">
          <span class="order-number">订单号: {{ order.order_number }}</span>
          <span class="order-status" :class="getStatusClass(order.status)">
            {{ getStatusText(order.status) }}
          </span>
        </div>

        <div class="order-items">
          <div 
            v-for="item in order.items" 
            :key="item.order_item_id"
            class="order-item"
          >
            <el-image 
              :src="getProductImage(item.product)" 
              class="item-image"
              fit="cover"
            >
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <div class="item-info">
              <h4 class="item-name">{{ item.product_name || '商品' }}</h4>
              <p class="item-spec">规格: 默认</p>
              <div class="item-price">¥{{ item.product_price }} x {{ item.quantity }}</div>
            </div>
            <div class="item-subtotal">
              小计: ¥{{ item.subtotal }}
            </div>
          </div>
        </div>

        <div class="order-footer">
          <div class="order-total">
            实付: <span class="total-amount">¥{{ order.total_amount }}</span>
          </div>
          <div class="order-actions">
            <el-button 
              v-if="order.status === 'pending'"
              type="primary" 
              size="small"
              @click="handlePay(order)"
            >
              立即支付
            </el-button>
            <el-button 
              v-if="order.status === 'pending'"
              type="default" 
              size="small"
              @click="handleCancel(order)"
            >
              取消订单
            </el-button>
            <el-button 
              v-if="order.status === 'paid'"
              type="default" 
              size="small"
              @click="handleConfirm(order)"
            >
              确认收货
            </el-button>
            <el-button 
              v-if="order.status === 'completed'"
              type="default" 
              size="small"
              @click="handleViewDetail(order)"
            >
              查看详情
            </el-button>
          </div>
        </div>

        <div class="order-meta">
          <span class="order-time">创建时间: {{ formatDate(order.created_at) }}</span>
          <span v-if="order.paid_at" class="order-time">支付时间: {{ formatDate(order.paid_at) }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, Picture } from '@element-plus/icons-vue'
import { getMyOrders, cancelOrder, processPayment } from '@/api/orders'

interface OrderItem {
  order_item_id: number
  product_id: number
  product_name: string
  product_price: number
  quantity: number
  subtotal: number
  product?: {
    product_id: number
    cover_image?: string
  }
}

interface Order {
  order_id: number
  order_number: string
  total_amount: number
  status: string
  payment_status: string
  shipping_address: string
  recipient_name: string
  recipient_phone: string
  created_at: string
  paid_at?: string
  items: OrderItem[]  // 关键修复：改为 items 而不是 order_items
}

const router = useRouter()
const orders = ref<Order[]>([])
const loading = ref(true)
const filterStatus = ref('all')

const fetchMyOrders = async () => {
  try {
    loading.value = true
    console.log('📦 开始获取订单列表...')
    
    const params = filterStatus.value === 'all' ? {} : { status: filterStatus.value }
    const response = await getMyOrders(params)
    
    console.log('✅ 订单API响应:', response)
    
    // 关键修复：正确解析响应结构
    if (response && (response.success || response.code === 200)) {
      orders.value = response.data || []
      console.log('📦 解析到的订单:', orders.value)
    } else {
      console.warn('⚠️ 订单API响应格式异常')
      orders.value = []
    }
  } catch (error: any) {
    console.error('❌ 获取订单失败:', error)
    ElMessage.error('获取订单失败: ' + (error.response?.data?.message || error.message))
    orders.value = []
  } finally {
    loading.value = false
  }
}

const getProductImage = (product: any) => {
  if (product?.cover_image) {
    // 这里需要根据你的图片路径处理逻辑来调整
    return product.cover_image
  }
  return ''
}

const getStatusClass = (status: string) => {
  switch (status) {
    case 'pending': return 'status-pending'
    case 'paid': return 'status-paid'
    case 'completed': return 'status-completed'
    case 'cancelled': return 'status-cancelled'
    case 'refunded': return 'status-cancelled'
    default: return 'status-pending'
  }
}

const getStatusText = (status: string) => {
  switch (status) {
    case 'pending': return '待支付'
    case 'paid': return '已支付'
    case 'completed': return '已完成'
    case 'cancelled': return '已取消'
    case 'refunded': return '已退款'
    default: return '未知状态'
  }
}

const handlePay = async (order: Order) => {
  try {
    console.log('💰 支付订单:', order.order_id)
    const response = await processPayment(order.order_id)
    
    if (response.success) {
      ElMessage.success('支付成功！')
      // 刷新订单列表
      await fetchMyOrders()
    } else {
      throw new Error(response.message || '支付失败')
    }
  } catch (error: any) {
    console.error('❌ 支付失败:', error)
    ElMessage.error(error.response?.data?.message || error.message || '支付失败')
  }
}

const handleCancel = async (order: Order) => {
  try {
    await ElMessageBox.confirm('确定要取消这个订单吗？', '提示', {
      type: 'warning'
    })
    
    console.log('❌ 取消订单:', order.order_id)
    await cancelOrder(order.order_id)
    ElMessage.success('取消成功')
    await fetchMyOrders()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('❌ 取消失败:', error)
      ElMessage.error('取消失败')
    }
  }
}

const handleConfirm = async (order: Order) => {
  try {
    await ElMessageBox.confirm('确定要确认收货吗？', '提示', {
      type: 'warning'
    })
    
    // 这里需要添加确认收货的API调用
    ElMessage.success('确认收货成功')
    await fetchMyOrders()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('确认失败')
    }
  }
}

const handleViewDetail = (order: Order) => {
  ElMessage.info('订单详情功能开发中')
  console.log('查看订单详情:', order)
}

const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

onMounted(() => {
  fetchMyOrders()
})
</script>

<style scoped>
.orders-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 16px;
}

.page-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
  color: white;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.order-filter {
  margin-bottom: 20px;
  background: white;
  padding: 16px;
  border-radius: 12px;
}

.loading-container,
.empty-container {
  padding: 40px 0;
}

.orders-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.order-card {
  background: white;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.order-number {
  font-size: 14px;
  color: #666;
}

.order-status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-pending {
  background: #fff7e6;
  color: #fa8c16;
}

.status-paid {
  background: #e6f7ff;
  color: #1890ff;
}

.status-completed {
  background: #f6ffed;
  color: #52c41a;
}

.status-cancelled {
  background: #fff2f0;
  color: #ff4d4f;
}

.order-items {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 12px;
}

.order-item {
  display: flex;
  gap: 12px;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f5f5f5;
}

.order-item:last-child {
  border-bottom: none;
}

.item-image {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  flex-shrink: 0;
}

.image-error {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  border-radius: 8px;
  color: #999;
}

.item-info {
  flex: 1;
}

.item-name {
  margin: 0 0 4px 0;
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.item-spec {
  margin: 0 0 4px 0;
  font-size: 12px;
  color: #999;
}

.item-price {
  font-size: 14px;
  font-weight: 600;
  color: #ff4757;
}

.item-subtotal {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  min-width: 80px;
  text-align: right;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
  margin-bottom: 8px;
}

.order-total {
  font-size: 16px;
  color: #333;
}

.total-amount {
  font-size: 18px;
  font-weight: 700;
  color: #ff4757;
}

.order-actions {
  display: flex;
  gap: 8px;
}

.order-meta {
  display: flex;
  flex-direction: column;
  gap: 4px;
  font-size: 12px;
  color: #999;
}

.order-time {
  font-size: 11px;
}
</style>